<template>
  <div class="financial-dashboard">
    <!-- 时间维度选择器 -->
    <el-card class="filter-card">
      <el-form :inline="true">
        <el-form-item label="统计维度">
          <el-radio-group v-model="timeDimension" @change="refreshData">
            <el-radio-button value="week">周</el-radio-button>
            <el-radio-button value="month">月</el-radio-button>
            <el-radio-button value="quarter">季</el-radio-button>
            <el-radio-button value="year">年</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择年份" style="width: 200px;">
          <el-select v-model="compareYear" @change="refreshData">
            <el-option
              v-for="year in availableYears"
              :key="year"
              :label="year === currentYear ? '本年' : `${year}年`"
              :value="year"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <!-- 营业收入卡片 -->
      <el-col :span="6">
        <el-card class="stat-card" :style="cardStyle('income')" shadow="hover">
          <div class="stat-content">
            <div class="stat-title" :style="titleStyle('income')">
              营业收入
              <el-tooltip :content="`${yearLabel}营业收入`" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
            <div class="stat-value" :style="valueStyle('income')">
              {{ formatNumber(currentStats.income) }}
            </div>
            <div class="comparison" v-if="showComparison">
              <span class="compare-label">对比{{ comparisonYearLabel }}:</span>
              <span class="compare-value" :style="compareStyle(currentStats.income, compareStats.income)">
                {{ formatNumber(Math.abs(currentStats.income - compareStats.income)) }}
                <el-icon>
                  <CaretTop v-if="currentStats.income >= compareStats.income" />
                  <CaretBottom v-else />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 其他三个卡片结构相同 -->
      <!-- 净利润卡片 -->
      <el-col :span="6">
        <el-card class="stat-card" :style="cardStyle('profit')" shadow="hover">
          <div class="stat-content">
            <div class="stat-title" :style="titleStyle('profit')">
              净利润
              <el-tooltip :content="`${yearLabel}净利润`" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
            <div class="stat-value" :style="valueStyle('profit')">
              {{ formatNumber(currentStats.profit) }}
            </div>
            <div class="comparison" v-if="showComparison">
              <span class="compare-label">对比{{ comparisonYearLabel }}:</span>
              <span class="compare-value" :style="compareStyle(currentStats.profit, compareStats.profit)">
                {{ formatNumber(Math.abs(currentStats.profit - compareStats.profit)) }}
                <el-icon>
                  <CaretTop v-if="currentStats.profit >= compareStats.profit" />
                  <CaretBottom v-else />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 销售订单数卡片 -->
      <el-col :span="6">
        <el-card class="stat-card" :style="cardStyle('orders')" shadow="hover">
          <div class="stat-content">
            <div class="stat-title" :style="titleStyle('orders')">
              销售订单数
              <el-tooltip :content="`${yearLabel}订单数`" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
            <div class="stat-value" :style="valueStyle('orders')">
              {{ formatNumber(currentStats.orders) }}
            </div>
            <div class="comparison" v-if="showComparison">
              <span class="compare-label">对比{{ comparisonYearLabel }}:</span>
              <span class="compare-value" :style="compareStyle(currentStats.orders, compareStats.orders)">
                {{ formatNumber(Math.abs(currentStats.orders - compareStats.orders)) }}
                <el-icon>
                  <CaretTop v-if="currentStats.orders >= compareStats.orders" />
                  <CaretBottom v-else />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 本金卡片 -->
      <el-col :span="6">
        <el-card class="stat-card" :style="cardStyle('capital')" shadow="hover">
          <div class="stat-content">
            <div class="stat-title" :style="titleStyle('capital')">
              本金
              <el-tooltip :content="`${yearLabel}库存成本`" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
            <div class="stat-value" :style="valueStyle('capital')">
              {{ formatNumber(currentStats.capital) }}
            </div>
            <div class="comparison" v-if="showComparison">
              <span class="compare-label">对比{{ comparisonYearLabel }}:</span>
              <span class="compare-value" :style="compareStyle(currentStats.capital, compareStats.capital, true)">
                {{ formatNumber(Math.abs(currentStats.capital - compareStats.capital)) }}
                <el-icon>
                  <CaretTop v-if="currentStats.capital <= compareStats.capital" />
                  <CaretBottom v-else />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收入支出趋势图 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>{{ yearLabel }}收入支出趋势分析</span>
          <div v-if="showComparison" class="comparison-legend">
            <span class="current-legend">
              <span class="legend-color" style="background: #67C23A;"></span>
              {{ yearLabel }}
            </span>
            <span class="compare-legend">
              <span class="legend-color" style="background: #409EFF;"></span>
              {{ comparisonYearLabel }}
            </span>
          </div>
        </div>
      </template>
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { salesOrderApi, inventoryApi } from '../../api'
import { ElMessage } from 'element-plus'

// 响应式变量
const timeDimension = ref('month')
const chartRef = ref(null)
let chartInstance = null

// 年份选择相关
const currentYear = new Date().getFullYear()
const compareYear = ref(currentYear)
const availableYears = computed(() => {
  const years = []
  for (let i = currentYear; i >= currentYear - 5; i--) {
    years.push(i)
  }
  return years
})

// 计算显示的年份标签
const yearLabel = computed(() => {
  return compareYear.value === currentYear ? '本年' : `${compareYear.value}年`
})


// 是否显示对比数据
const showComparison = computed(() => {
  return true
})

// 统计数据
const currentStats = ref({
  income: 0,
  profit: 0,
  orders: 0,
  capital: 0
})

const compareStats = ref({
  income: 0,
  profit: 0,
  orders: 0,
  capital: 0
})

// 获取日期范围 (支持历史年份)
const getDateRange = (year = currentYear) => {
  // 创建基准日期（使用指定年份的当前月日）
  const baseDate = new Date(year, new Date().getMonth(), new Date().getDate())
  const start = new Date(baseDate)
  const end = new Date(baseDate)
  
  // 根据时间维度调整范围
  switch (timeDimension.value) {
    case 'week':
      // 计算本周一
      const dayOfWeek = baseDate.getDay() // 0(周日)到6(周六)
      start.setDate(baseDate.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1))
      start.setHours(0, 0, 0, 0) // 设置为周一00:00:00
      // 计算本周日
      end.setDate(start.getDate() + 6)
      end.setHours(23, 59, 59, 999) // 设置为周日23:59:59.999
      break
      
    case 'month':
      // 当月第一天
      start.setDate(1)
      start.setHours(0, 0, 0, 0)
      // 当月最后一天
      end.setMonth(baseDate.getMonth() + 1, 0)
      end.setHours(23, 59, 59, 999)
      break
      
    case 'quarter':
      // 计算季度起始月 (0-2: Q1, 3-5: Q2, 6-8: Q3, 9-11: Q4)
      const quarterStartMonth = Math.floor(baseDate.getMonth() / 3) * 3
      // 季度第一天
      start.setMonth(quarterStartMonth, 1)
      start.setHours(0, 0, 0, 0)
      // 季度最后一天
      end.setMonth(quarterStartMonth + 3, 0)
      end.setHours(23, 59, 59, 999)
      break
      
    case 'year':
      // 年初第一天
      start.setMonth(0, 1)
      start.setHours(0, 0, 0, 0)
      // 年末最后一天
      end.setMonth(11, 31)
      end.setHours(23, 59, 59, 999)
      break
  }
  
  console.log(`时间范围: ${start.toLocaleString()} 到 ${end.toLocaleString()}`)
  return { start, end }
}

// 获取时间标签
const getTimeLabels = () => {
  const now = new Date()
  switch (timeDimension.value) {
    case 'week':
      return ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    case 'month':
      const days = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate()
      return Array.from({ length: days }, (_, i) => `${i + 1}日`)
    case 'quarter':
      const quarterStart = Math.floor(now.getMonth() / 3) * 3
      return [0, 1, 2].map(i => `${quarterStart + i + 1}月`)
    case 'year':
      return Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
  }
}

// 处理数据分组
const processData = (data, labels) => {
  const result = new Array(labels.length).fill(0)
  
  if (!data || data.length === 0) return result
  
  data.forEach(item => {
    const date = new Date(item.salesOrderDate)
    let index = -1
    
    switch (timeDimension.value) {
      case 'week':
        index = date.getDay() === 0 ? 6 : date.getDay() - 1
        break
      case 'month':
        index = date.getDate() - 1
        break
      case 'quarter':
        index = date.getMonth() % 3
        break
      case 'year':
        index = date.getMonth()
        break
    }
    
    if (index >= 0 && index < result.length) {
      result[index] += item.totalAmount || 0
    }
  })
  
  return result
}

// 渲染图表
// 修改后的图表渲染函数
const renderChart = (currentData, compareData) => {
  if (!chartRef.value) return
  
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }
  
  const labels = getTimeLabels()
  const currentIncomeData = processData(currentData, labels)
  const currentProfitData = processData(
    currentData?.map(item => ({ ...item, totalAmount: item.totalProfit || 0 })) || [],
    labels
  )
  
  const compareIncomeData = processData(compareData, labels)
  const compareProfitData = processData(
    compareData?.map(item => ({ ...item, totalAmount: item.totalProfit || 0 })) || [],
    labels
  )
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: [
        `${yearLabel.value}收入`, 
        `${yearLabel.value}利润`, 
        `${comparisonYearLabel.value}收入`, 
        `${comparisonYearLabel.value}利润`
      ]
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: labels,
      axisLabel: {
        rotate: timeDimension.value === 'month' ? 45 : 0,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 元'
      }
    },
    series: [
      {
        name: `${yearLabel.value}收入`,
        type: 'bar',
        data: currentIncomeData,
        itemStyle: { color: '#34c38f' }
      },
      {
        name: `${yearLabel.value}利润`,
        type: 'bar',
        data: currentProfitData,
        itemStyle: { color: '#f1b44c' }
      },
      {
        name: `${comparisonYearLabel.value}收入`,
        type: 'bar',
        data: compareIncomeData,
        itemStyle: { color: '#556ee6' }
      },
      {
        name: `${comparisonYearLabel.value}利润`,
        type: 'bar',
        data: compareProfitData,
        itemStyle: { color: '#50a5f1' }
      }
    ]
  }
  
  chartInstance.setOption(option, true)
  
  const handleResize = () => chartInstance.resize()
  window.addEventListener('resize', handleResize)
  
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    chartInstance?.dispose()
  })
}

// 更新统计数据
const updateStats = (currentData, compareData, currentInventoryData, compareInventoryData) => {
  currentStats.value = {
    income: currentData?.reduce((sum, item) => sum + (item.totalAmount || 0), 0) || 0,
    profit: currentData?.reduce((sum, item) => sum + (item.totalProfit || 0), 0) || 0,
    orders: currentData?.length || 0,
    capital: currentInventoryData?.reduce((sum, item) => sum + (item.amount || 0), 0) || 0
  }

  compareStats.value = showComparison.value ? {
    income: compareData?.reduce((sum, item) => sum + (item.totalAmount || 0), 0) || 0,
    profit: compareData?.reduce((sum, item) => sum + (item.totalProfit || 0), 0) || 0,
    orders: compareData?.length || 0,
    capital: compareInventoryData?.reduce((sum, item) => sum + (item.amount || 0), 0) || 0
  } : {
    income: 0,
    profit: 0,
    orders: 0,
    capital: 0
  }
}

// 比较值样式
const compareStyle = (current, compare, isReverse = false) => {
  const isPositive = isReverse ? current <= compare : current >= compare
  return {
    color: isPositive ? '#52C41A' : '#FF4D4F',
    display: 'flex',
    alignItems: 'center',
    gap: '4px'
  }
}
const colorConfig = {
  income: {
    primary: '#52C41A',
    light: '#F6FFED',
    text: '#135200',
    border: '#B7EB8F'
  },
  profit: {
    primary: '#1890FF',
    light: '#E6F7FF',
    text: '#003A8C',
    border: '#91D5FF'
  },
  orders: {
    primary: '#FAAD14',
    light: '#FFFBE6',
    text: '#AD6800',
    border: '#FFE58F'
  },
  capital: {
    primary: '#722ED1',
    light: '#F9F0FF',
    text: '#391085',
    border: '#D3ADF7'
  }
}
const cardStyle = (type) => ({
  borderTop: `3px solid ${colorConfig[type].primary}`,
  backgroundColor: colorConfig[type].light
})

const titleStyle = (type) => ({
  color: colorConfig[type].text,
  fontWeight: '500'
})

const valueStyle = (type) => ({
  color: colorConfig[type].primary,
  fontSize: '24px',
  fontWeight: 'bold'
})


// 修改后的年份标签计算
const comparisonYearLabel = computed(() => {
  return `${compareYear.value - 1}年`
})

// 修改后的获取数据函数
const fetchData = async () => {
  try {
    // 获取当前选择年份数据
    const { start: currentStart, end: currentEnd } = getDateRange(compareYear.value)
    const currentRes = await salesOrderApi.getListAll({ 
      startDate: currentStart, 
      endDate: currentEnd 
    })
    const currentInventoryRes = await inventoryApi.getListAll({
      startDate: currentStart,
      endDate: currentEnd
    })

    // 总是获取对比年份数据
    const { start: compareStart, end: compareEnd } = getDateRange(compareYear.value - 1)
    const compareRes = await salesOrderApi.getListAll({ 
      startDate: compareStart, 
      endDate: compareEnd 
    })
    const compareInventoryRes = await inventoryApi.getListAll({
      startDate: compareStart,
      endDate: compareEnd
    })

    updateStats(
      currentRes.data, 
      compareRes.data,
      currentInventoryRes.data,
      compareInventoryRes.data
    )
    renderChart(currentRes.data, compareRes.data)
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('获取数据失败:', error)
    renderChart([], [])
    currentStats.value = { income: 0, profit: 0, orders: 0, capital: 0 }
    compareStats.value = { income: 0, profit: 0, orders: 0, capital: 0 }
  }
}

// 刷新数据
const refreshData = () => {
  fetchData()
}

// 数字格式化
const formatNumber = (num) => {
  return num?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") || '0'
}

// 初始化
onMounted(() => {
  nextTick(() => {
    fetchData()
  })
})

// 监听变化
watch([timeDimension, compareYear], fetchData)
</script>

<style scoped>
.financial-dashboard {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  padding: 12px;
}

.stat-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
}

.stat-value {
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: bold;
}

.comparison {
  font-size: 12px;
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
}

.compare-label {
  color: #888;
}

.compare-value {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.chart-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comparison-legend {
  display: flex;
  gap: 16px;
  font-size: 12px;
}

.legend-color {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 2px;
  margin-right: 4px;
}
</style>